package com.zsyc.util;

import com.zsyc.model.Task;
import javafx.application.Platform;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
// import javafx.scene.media.Media;
// import javafx.scene.media.MediaPlayer;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;
import java.util.logging.Level;
import java.util.prefs.Preferences;

/**
 * 提醒服务类
 */
public class ReminderService {
    private static final Logger LOGGER = Logger.getLogger(ReminderService.class.getName());
    private static final String PREF_NODE = "com.zsyc.settings";
    private static Timer reminderTimer;
    private static Preferences prefs;
    
    /**
     * 初始化提醒服务
     */
    public static void initialize() {
        prefs = Preferences.userRoot().node(PREF_NODE);
        startReminderTimer();
    }
    
    /**
     * 启动提醒定时器
     */
    private static void startReminderTimer() {
        if (reminderTimer != null) {
            reminderTimer.cancel();
        }
        
        reminderTimer = new Timer(true);
        reminderTimer.scheduleAtFixedRate(new TimerTask() {
            @Override
            public void run() {
                checkReminders();
            }
        }, 0, 60000); // 每分钟检查一次
        
        LOGGER.info("提醒服务已启动");
    }
    
    /**
     * 检查提醒
     */
    private static void checkReminders() {
        try {
            List<Task> tasks = Task.getAllTasks();
            LocalDateTime now = LocalDateTime.now();
            
            for (Task task : tasks) {
                if (task.isEnableReminder() && !task.isCompleted() && task.getDueDate() != null) {
                    checkTaskReminder(task, now);
                }
            }
        } catch (Exception e) {
            LOGGER.log(Level.SEVERE, "检查提醒失败", e);
        }
    }
    
    /**
     * 检查单个任务的提醒
     */
    private static void checkTaskReminder(Task task, LocalDateTime now) {
        LocalDateTime dueDateTime = task.getDueDate().atTime(9, 0); // 默认上午9点
        LocalDateTime reminderTime = calculateReminderTime(dueDateTime, task.getReminderTime(), task.getReminderUnit());
        
        if (now.isAfter(reminderTime) && now.isBefore(dueDateTime)) {
            // 检查是否已经提醒过
            String reminderKey = "reminder_" + task.getTaskId();
            if (!prefs.getBoolean(reminderKey, false)) {
                showReminder(task);
                prefs.putBoolean(reminderKey, true);
            }
        }
    }
    
    /**
     * 计算提醒时间
     */
    private static LocalDateTime calculateReminderTime(LocalDateTime dueDateTime, int reminderTime, String reminderUnit) {
        if ("天".equals(reminderUnit)) {
            return dueDateTime.minusDays(reminderTime);
        } else {
            return dueDateTime.minusHours(reminderTime);
        }
    }
    
    /**
     * 显示提醒
     */
    private static void showReminder(Task task) {
        Platform.runLater(() -> {
            // 弹窗提醒
            if (isPopupReminderEnabled()) {
                Alert alert = new Alert(AlertType.INFORMATION);
                alert.setTitle("任务提醒");
                alert.setHeaderText("任务即将到期");
                alert.setContentText(
                    "任务: " + task.getTitle() + "\n" +
                    "描述: " + task.getDescription() + "\n" +
                    "截止日期: " + task.getDueDate() + "\n" +
                    "分类: " + task.getCategory()
                );
                alert.showAndWait();
            }
            
            // 声音提醒
            if (isSoundReminderEnabled()) {
                playReminderSound();
            }
            
            LOGGER.info("已发送任务提醒: " + task.getTitle());
        });
    }
    
    /**
     * 播放提醒声音
     */
    private static void playReminderSound() {
        try {
            // 这里可以添加声音文件路径
            // Media sound = new Media(getClass().getResource("/sounds/reminder.wav").toExternalForm());
            // MediaPlayer mediaPlayer = new MediaPlayer(sound);
            // mediaPlayer.play();
            LOGGER.info("播放提醒声音");
        } catch (Exception e) {
            LOGGER.log(Level.WARNING, "播放提醒声音失败", e);
        }
    }
    
    /**
     * 检查是否启用弹窗提醒
     */
    private static boolean isPopupReminderEnabled() {
        return prefs.getBoolean("popupReminder", true);
    }
    
    /**
     * 检查是否启用声音提醒
     */
    private static boolean isSoundReminderEnabled() {
        return prefs.getBoolean("soundReminder", true);
    }
    
    /**
     * 停止提醒服务
     */
    public static void stop() {
        if (reminderTimer != null) {
            reminderTimer.cancel();
            reminderTimer = null;
        }
        LOGGER.info("提醒服务已停止");
    }
    
    /**
     * 重置任务提醒状态
     */
    public static void resetTaskReminder(int taskId) {
        String reminderKey = "reminder_" + taskId;
        prefs.remove(reminderKey);
    }
}
